package com.wy.network.Transfer.basic;



import com.wy.network.util.StreamUtils;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;

/**
 * @author 吴宇~
 * @motto 我 亦无他，唯手熟尔。
 * @edition jdk1.8
 * @reflection 0-1 喧闹任其喧闹，自由我自为之，我自风情万种，与世无争。
 * @date 2023/03/17/17:36
 * //客户端上传图片到服务器，服务器并且回复消息，图片我是传过来了，但是报错了
 */
public class Server_ {
    public static void main(String[] args) throws Exception {

        String fileName="";
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\transfer\\Transfer\\basic\\parameter.properties"));
        String receiveFilePath = properties.getProperty("ReceiveFilePath");
        String port = properties.getProperty("port");
        int Port = Integer.parseInt(port);


        /**
         * 二进制文件都能传输，Multisim 文件也能传输，操作空间又增加了，但是单纯一个文件的话不能传输，必须得有后缀的文件才可以传输
         */
        /**
         * 服务端在本机监听8888端口
         * 等待监听
         * 读取客户端发生的数据
         * 通过socket得到输入流,在这个输入流上面，就已经是客户端传的东西了，
         * 加了Buff的输入流
         */
        ServerSocket serverSocket = new ServerSocket(Port);
        System.out.println("服务端8888接口在监听。。");
        Socket accept = serverSocket.accept();
        //--------------------------
        InputStream inputStream1 = accept.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream1));
        String s = bufferedReader.readLine();
        System.out.println(s);
        fileName=s;

        String fillPath = receiveFilePath+fileName;
        //--------------------------

        InputStream inputStream = accept.getInputStream();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
        byte[] bytes1 = StreamUtils.streamToByteArray(bufferedInputStream);
        FileOutputStream fileOutputStream = new FileOutputStream(fillPath);
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
        bufferedOutputStream.write(bytes1);
        bufferedOutputStream.flush();//使用了BufferedOutput的话，在传输完标志置之前尽量刷新一下

        //向客户端恢复收到图片
        //这儿字符流字节流转换汉字和字母的话都差不多，除非图片，别被老韩糊住了
        BufferedOutputStream bufferedOutputStream1 = new BufferedOutputStream(accept.getOutputStream());
        bufferedOutputStream1.write("服务端已接收到您发送的信息，over".getBytes());
        bufferedOutputStream1.flush();
        accept.shutdownOutput();


        //--------
        bufferedReader.close();
        //--------
        bufferedOutputStream1.close();
        bufferedOutputStream.close();
        bufferedInputStream.close();
        accept.close();
        serverSocket.close();

    }
}
